package com.shujia.wyh.day11;

import java.util.ArrayList;

/*
    去除集合中自定义对象的重复值(对象的成员变量值都相同)

 */
public class ListTest2 {
    public static void main(String[] args) {
        //创建集合对象
        ArrayList list = new ArrayList();

        //创建元素对象
        //创建学生对象
        Student s1 = new Student("史俊超", 18);
        Student s2 = new Student("杨志", 17);
        Student s3 = new Student("张玮", 18);
        Student s4 = new Student("陆澳", 19);
        Student s5 = new Student("史俊超", 18);

        list.add(s1);
        list.add(s2);
        list.add(s3);
        list.add(s4);
        list.add(s5);
        System.out.println("去重前的集合list: " + list);

        //创建一个新的集合对象
        ArrayList list2 = new ArrayList();

        //遍历旧集合
        for (int i = 0; i < list.size(); i++) {
            Student student = (Student) list.get(i);
            //contains()方法底层是采用equals方法进行比较的，而元素类型Student中并没有重写，所以使用是Object中的equals方法
            //而Object中的equals方法默认比较的是地址值
            if (!list2.contains(student)) {
                list2.add(student);
            }
        }

        System.out.println("去重前的集合list2: " + list2);
    }
}

/**
 *
 *    //list2.contains(student)
 *     public boolean contains(Object o) {
 *     // o -- student
 *         return indexOf(o) >= 0;
 *     }
 *
 *
 *     public int indexOf(Object o) {
 *     //o -- student
 *         if (o == null) {
 *             for (int i = 0; i < size; i++)
 *                 if (elementData[i]==null)
 *                     return i;
 *         } else {
 *             for (int i = 0; i < size; i++)
 *                 if (o.equals(elementData[i]))
 *                     return i;
 *         }
 *         return -1;
 *     }
 *
 *
 */
